package com.cheung.leetcode.str;

public class LC14 {

    public static String longestCommonPrefix(String[] strs) {


        int min = strs[0].length();
        int index = 0;
        for (int i = 0; i < strs.length; i++) {
            if (strs[i].length() < min) {
                min = strs[i].length();
                index = i;
            }
        }
        StringBuilder sb = new StringBuilder(strs[index]);
        // 下标index的元素最短
        if (sb.isEmpty()) {
            return "";
        }


        while (!sb.isEmpty()) {
            boolean flag = true;
            for (String str : strs) {
                // 所有元素都是以sb字符串开始的
                flag = flag && str.startsWith(sb.toString());
            }
            if (flag) {
                return sb.toString();
            } else {
                sb.deleteCharAt(sb.length() - 1);
            }
        }

        return sb.toString();
    }

    public static String longestCommonPrefixV2(String[] strs) {
        // 选第一个元素作为最大公共前缀
        String prefix = strs[0];
        // 从第2个元素开始，遍历每个元素
        for (int i = 1; i < strs.length; i++) {
            // 循环判断，已有的前缀是不是当前字符串的开头，如果不是，前缀减一位，接着判断，直到是或前缀为空
            while (strs[i].indexOf(prefix) != 0) {
                prefix = prefix.substring(0, prefix.length() - 1);
            }
        }
        return prefix;
    }


    public static void main(String[] args) {
//        String[] strs = {"flower", "flow", "flight"};
        String[] strs = {"dog", "racecar", "car"};
        System.out.println(longestCommonPrefixV2(strs));
        System.out.println("ab".indexOf(""));
    }
}
